package com.hssoftvn.android.apps.callmessmoneycontroller.modules;

import android.content.Context;
import android.content.IntentFilter;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

import com.hssoftvn.android.apps.callmessmoneycontroller.enums.SConstanst;
import com.hssoftvn.android.apps.callmessmoneycontroller.util.SUtils;

public class PhoneStateHelper {
	
	//private static PhoneStateHelper mInstance = null;
	public static TelephonyManager p_TelephonyManager = null;
	public static TinyPhoneStateListener p_myPhoneStateListener = null;
	private static OpenCellID sOpenCellID = new OpenCellID();
	public PhoneStateHelper() {
		// TODO Auto-generated constructor stub
	}
	public static void requestForCellLocation(){
		p_TelephonyManager = (TelephonyManager) SUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
		CellLocation cellLocation = (GsmCellLocation)p_TelephonyManager.getCellLocation();
		try {
			String networkOperator = p_TelephonyManager.getNetworkOperator();
			String mcc = networkOperator.substring(0, 3);
			String mnc = networkOperator.substring(3);
			sOpenCellID.setCallID(((GsmCellLocation) cellLocation).getCid());
			sOpenCellID.setCallLac(((GsmCellLocation) cellLocation).getLac());
			sOpenCellID.setMcc(mcc);
			sOpenCellID.setMnc(mnc);
			sOpenCellID.GetOpenCellID();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	public static void init(){
		p_myPhoneStateListener = new TinyPhoneStateListener();
		IntentFilter filter = new IntentFilter(SConstanst.INTENT_ACTION_NOTIFY_OPENCELLID_RESULT);
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		SUtils.getAppContext().registerReceiver(p_myPhoneStateListener, filter);
	}
	public static void unregisterCellLocation(){
		if (p_myPhoneStateListener!=null && p_TelephonyManager!=null){
			try {
				SUtils.getAppContext().unregisterReceiver(p_myPhoneStateListener);
				p_myPhoneStateListener = null;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d(SUtils.TAG, e.getMessage());
			}
		}
	}
	
	public static void terminate(){
		try {
			unregisterCellLocation();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
